package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/*
* 金文网络
* */
@Slf4j
public class Plugin_ECARD_P028 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }
    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            HashMap<String, Object> resParams = new HashMap<>();
            String accountVal = String.valueOf(data.get("AccountVal"));
            resParams.put("appId",apiConfig.getString("AppId"));
            long timestamp = Instant.now().toEpochMilli();
            resParams.put("timestamp",timestamp);
            resParams.put("thirdOrderNo",data.get("ChannelOrderCode"));
            resParams.put("brandSpecCode",data.get("SUPProductId"));
            resParams.put("account",accountVal);
            String type = getAccountType(accountVal);
            String sign = generateSignature(resParams, apiConfig.getString("SecretKey"));

            resParams.put("notifyUrl",apiConfig.getString("NotifyUrl"));//不加入签名
            resParams.put("userType",type);//不加入签名
            resParams.put("signature",sign);//签名

            String submitUrl = apiConfig.getString("SubmitUrl");
            String res = HttpTool.sendPost2(submitUrl, resParams);
            JSONObject resObject = JSONObject.parseObject(res);
            String code = resObject.getString("code");
            String message = resObject.getString("message");
            //String success = resObject.getString("success");
                if(code.equals("0") || code.equals("04")){
                    return ChannelResult.IN_PROCESS("充值中");
                }else if (code.equals("-1")
                        || code.equals("01")
                        || code.equals("03")
                        || code.equals("06")
                        || code.equals("6013")
                        || code.equals("6022")
                        || code.equals("6023")
                        || code.equals("6025")
                        || code.equals("6026")
                        || code.equals("10011")
                        || code.equals("10083")
                        || code.equals("20002")
                        || code.equals("9001")
                        || code.equals("500")){
                    return ChannelResult.error(message);
                }
                return ChannelResult.FAILED(message);
        }catch (Exception e){
            e.printStackTrace();
            log.error("金文网络订单接口错误：",e);
            return  ChannelResult.error("金文网络订单接口错误");
        }
    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {
        try {
            HashMap<String, Object> queryParams = new HashMap<>();
            queryParams.put("appId",apiConfig.getString("AppId"));
            long timestamp = Instant.now().toEpochMilli();
            queryParams.put("timestamp",timestamp);
            queryParams.put("thirdOrderNo",data.get("ChannelOrderCode"));
            String sign = generateSignature(queryParams, apiConfig.getString("SecretKey"));
            queryParams.put("signature",sign);
            String queryUrl = apiConfig.getString("QueryUrl");
            String res = HttpTool.sendPost2(queryUrl, queryParams);
            JSONObject resObject = JSONObject.parseObject(res);
            String code = resObject.getString("code");
            String message = resObject.getString("message");
            //String success = resObject.getString("success");
            String value = resObject.getString("value");
                if (code.equals("0")) {
                    JSONObject parseObject = JSONObject.parseObject(value);
                    String orderStatus = parseObject.getString("orderStatus");
                    String orderStatusDes = parseObject.getString("orderStatusDes");
                    if (orderStatus.equals("SHIPMENTS_PREPARE")){
                        return ChannelResult.IN_PROCESS("充值中");
                    }else
                    if (orderStatus.equals("SHIPMENTS_SUCCESS")){
                        return  ChannelResult.success("充值成功");
                    }else
                    if (orderStatus.equals("SHIPMENTS_FAILED")){
                        return  ChannelResult.FAILED("充值失败");
                    }else{
                        return ChannelResult.error(orderStatusDes);
                    }
            }
            return ChannelResult.error(message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("金文网络查询订单接口错误：",e);
            return  ChannelResult.error("金文网络查询订单接口错误");
        }

    }

    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }


    /**
     * 判断 accountVal 的类型并返回对应的数字值。
     * 电话号码返回 6，QQ 号返回 1，微信号返回 5，其他情况返回空字符串。
     *
     * @param accountVal 账号值
     * @return 对应数字值，或者空字符串
     */
    public static String getAccountType(String accountVal) {
        if (isPhoneNumber(accountVal)) {
            return "6";
        } else if (isQQNumber(accountVal)) {
            return "1";
        } else if (isWeChatNumber(accountVal)) {
            return "5";
        } else {
            return "";
        }
    }

    private static boolean isPhoneNumber(String accountVal) {
        return accountVal.matches("\\d{11}");
    }
    private static boolean isQQNumber(String accountVal) {
        return accountVal.matches("\\d{5,12}");
    }
    private static boolean isWeChatNumber(String accountVal) {
        return accountVal.matches("^[-_a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$");
    }



    public static String generateSignature(Map<String, Object> params,String key) {
        // 使用TreeMap对参数按照ASCII码表顺序排序
        Map<String, Object> sortedParams = new TreeMap<>(params);
        // 拼接参数串
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            queryStringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        queryStringBuilder.deleteCharAt(queryStringBuilder.length() - 1); // 删除最后一个"&"字符
        // 拼接密钥
        queryStringBuilder.append(key);
        System.out.println(queryStringBuilder);
        // 对拼接后的字符串进行MD5加密
        String md5 = md5Encrypt(queryStringBuilder.toString());
        // 将加密结果转换成大写字母
        String uppercaseMd5 = md5.toUpperCase();
        return uppercaseMd5;
    }

    /**
     * 使用MD5算法对字符串进行加密
     * @param input 需要加密的字符串
     * @return 加密后的字符串
     */
    private static String md5Encrypt(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : md5Bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm is not available.", e);
        }
    }


}
